package com.example.tzc.musicplay1;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private MyServiceConnection serviceConnection;
    private MusicService.MusicBinder binder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(this, R.raw.music);
    }

    public void handlePlay(View view) {
        if (binder == null) {
            Toast.makeText(this, "还没有绑定服务", Toast.LENGTH_SHORT).show();
            return;
        }
        binder.play();
    }

    public void handlePause(View view) {
        if (binder == null) {
            Toast.makeText(this, "还没有绑定服务", Toast.LENGTH_SHORT).show();
            return;
        }
        binder.pause();
    }

    public void handleStartService(View view) {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
    }

    public void handleStopService(View view) {
        Intent intent = new Intent(this, MusicService.class);
        stopService(intent);
    }

    public void handleBindService(View view) {
        Intent  intent = new Intent(this, MusicService.class);
        serviceConnection = new MyServiceConnection();
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    public void handleUnbindService(View view) {
        unbindService(serviceConnection);
    }

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MusicService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
